const app = getApp();
const AJAX = app.$ajax,
 $wx = app.$wx;

Page({
  data: {
    settingStatus: 1
  },

  onLoad(){
    
  },

  //获取用户信息 
  getUserInfo(e) {
    let user_info = e.detail;
    $wx.isAuthorization('userInfo', (status) => {
      if(status){
        let _this = this, detail = e.detail;
        wx.login({
          success(res) {
            _this.login({
              code: res.code,
              encrypted_data: user_info.encryptedData,
              iv: user_info.iv,
              raw_data: user_info.rawData,
              signature: user_info.signature
            });
          }
        });
      }else{
        this.setData({
          settingStatus: 2
        });
      }
    });
  },

  //打开授权 
  openSetting(e) {
    let _this = this;
    $wx.isAuthorization('userInfo', (status) => {
      if (status) {
        _this.setData({
          settingStatus: 1
        });
      }
    });
  },

  /**
   * 登录
   * @param 'platform' 平台
   * @param 'code'
   * */ 
  login(params){
    params.loadType = 'default';
    params.loadMsg = '登录中...';

    AJAX.login(params).then(([status, res, msg]) => {
      if(status){
        wx.setStorageSync('token', res.userInfo.token);
        wx.setStorageSync('userInfo', res.userInfo)
        let page = getCurrentPages(),
          prve_page = page[1];
          
        if (prve_page) {
          let prve_page_pamas = prve_page.options;
          wx.navigateBack({
            success() {
              prve_page.onLoad(prve_page_pamas);
            }
          });
        } else {
          throw new Error('无返回 navigateBack 页');
        }
      }else{
        $wx.showToast(res[0].msg);
      }
    });
  }
});